import session from '@/utils/session'

const VISITED_VIEW_KEY = 'visitedView'

const setVisited = visitedViews => {
  session.set(VISITED_VIEW_KEY, visitedViews)
}

const tagsView = {
  namespaced: true,
  state: {
    visited: session.get(VISITED_VIEW_KEY) || [],
    cached: []
  },
  mutations: {
    addVisited: (state, route) => {
      if (state.visited.some(view => view.name === route.name)) return
      let privilegeId = route.meta.privilegeId
      let visitedItem = {
        name: route.name,
        title: route.meta.name || 'empty-name',
        path: route.path
      }
      if (privilegeId) {
        visitedItem.privilegeId = privilegeId
      }
      state.visited.push(visitedItem)
      if (route.meta && route.meta.cache) {
        state.cached.push(route.name)
      }
      setVisited(state.visited)
    },
    delVisited: (state, route) => {
      for (let [ind, item] of state.visited.entries()) {
        if (item.path === route.path) {
          state.visited.splice(ind, 1)
        }
      }
      for (let [ind, name] of state.cached.entries()) {
        if (name === route.name) {
          state.cached.splice(ind, 1)
        }
      }
      setVisited(state.visited)
    },
    closeOts: (state, route) => {
      const curView = new Array({
        name: route.name,
        title: route.meta.title || 'empty-name',
        path: route.path
      })
      state.visited = curView
      setVisited(curView)
    },
    closeAll: state => {
      state.visited = []
      setVisited([])
    }
  },
  actions: {
    addVisited({ commit }, route) {
      return new Promise(resolve => {
        commit('addVisited', route)
        resolve()
      })
    },
    delVisited({ commit, state }, route) {
      return new Promise(resolve => {
        commit('delVisited', route)
        resolve(state.visited)
      })
    },
    closeOts({ commit }, route) {
      return new Promise(resolve => {
        commit('closeOts', route)
        resolve()
      })
    },
    closeAll({ commit }) {
      return new Promise(resolve => {
        commit('closeAll')
        resolve()
      })
    }
  }
}

export default tagsView
